<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>iOS UIViewController和UIView的生命周期 | Albert Yuan's Blog</title><meta name="keywords" content="Objective-c,Foundation"><meta name="author" content="Albert Yuan"><meta name="copyright" content="Albert Yuan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="referrer" content="no-referrer"><meta name="description" content="123456789101112131415161718192021222324252627282930&#x2F;&#x2F; 类的初始化方法+ (void)initialize;&#x2F;&#x2F;通过xib来初始化控制器- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ;&#x2F;&#x2F; 对象初始化方法- (i">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS UIViewController和UIView的生命周期">
<meta property="og:url" content="https://yllove.gitee.io/2022/10/28/iOS/iOS-ViewController%E4%B8%8EView%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/index.html">
<meta property="og:site_name" content="Albert Yuan&#39;s Blog">
<meta property="og:description" content="123456789101112131415161718192021222324252627282930&#x2F;&#x2F; 类的初始化方法+ (void)initialize;&#x2F;&#x2F;通过xib来初始化控制器- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ;&#x2F;&#x2F; 对象初始化方法- (i">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://yllove.gitee.io/img/defaultCover.png">
<meta property="article:published_time" content="2022-10-28T13:23:28.135Z">
<meta property="article:modified_time" content="2022-10-28T13:31:33.067Z">
<meta property="article:author" content="Albert Yuan">
<meta property="article:tag" content="Objective-c">
<meta property="article:tag" content="Foundation">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://yllove.gitee.io/img/defaultCover.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://yllove.gitee.io/2022/10/28/iOS/iOS-ViewController%E4%B8%8EView%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: {"appId":"X8NS0XSX99","apiKey":"b9d4530647c8b5bf7928a04c47752ad7","indexName":"albertyuan","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://fastly.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'iOS UIViewController和UIView的生命周期',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2022-10-28 21:31:33'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/blog/atom.xml" title="Albert Yuan's Blog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/img/defaultCover.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Albert Yuan's Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">iOS UIViewController和UIView的生命周期</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-28T13:23:28.135Z" title="发表于 2022-10-28 21:23:28">2022-10-28</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-10-28T13:31:33.067Z" title="更新于 2022-10-28 21:31:33">2022-10-28</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/iOS/">iOS</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/iOS/Objective-c/">Objective-c</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="iOS UIViewController和UIView的生命周期"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id><a href="#" class="headerlink" title></a></h2><figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 类的初始化方法</span></span><br><span class="line">+ (<span class="type">void</span>)initialize;</span><br><span class="line"><span class="comment">//通过xib来初始化控制器</span></span><br><span class="line">- (<span class="keyword">instancetype</span>)initWithNibName:(<span class="built_in">NSString</span> *)nibNameOrNil bundle:(<span class="built_in">NSBundle</span> *)nibBundleOrNil ;</span><br><span class="line"><span class="comment">// 对象初始化方法</span></span><br><span class="line">- (<span class="keyword">instancetype</span>)init;</span><br><span class="line"><span class="comment">// 从归档初始化</span></span><br><span class="line">- (<span class="keyword">instancetype</span>)initWithCoder:(<span class="built_in">NSCoder</span> *)coder;</span><br><span class="line"><span class="comment">//归档初始化后唤醒nib</span></span><br><span class="line">-(<span class="type">void</span>)awakeFromNib;</span><br><span class="line"><span class="comment">// 加载视图:当访问UIViewController的view属性时，view如果此时是nil，那么VC会自动调用loadView方法来初始化一个UIView并赋值给view属性。此方法用在初始化关键view，需要注意的是，在view初始化之前，不能先调用view的getter方法，否则将导致死循环（除非先调用了[super loadView];）如果没有重载loadView方法，则UIViewController会从nib或StoryBoard中查找默认的loadView，默认的loadView会返回一个空白的UIView对象。</span></span><br><span class="line">-(<span class="type">void</span>)loadView;</span><br><span class="line"><span class="comment">// 视图加载完成</span></span><br><span class="line">- (<span class="type">void</span>)viewDidLoad;</span><br><span class="line"><span class="comment">// 将要展示:,在view即将添加到视图层级中（显示给用户）且任意显示动画切换之前调用,此时self.view.superview为nil.这个方法中完成任何与试图显示相关的任务，例如改变视图方向、状态栏方向、视图显示样式等。</span></span><br><span class="line">-(<span class="type">void</span>)viewWillAppear:(<span class="type">BOOL</span>)animated;</span><br><span class="line"><span class="comment">// 将要布局子视图,self.view.superview为_UIParallaxDimmingView</span></span><br><span class="line">-(<span class="type">void</span>)viewWillLayoutSubviews;</span><br><span class="line"><span class="comment">// 已经布局子视图</span></span><br><span class="line">-(<span class="type">void</span>)viewDidLayoutSubviews;</span><br><span class="line"><span class="comment">// 已经展示:在view被添加到视图层级中，显示动画切换之后调用（这时view已经添加到supperView中）。在这个方法中执行视图显示相关附件任务，如果重载了这个方法，必须在方法中调用[supper viewDidAppear];,此时self.view.superview为UIViewControllerWrapperView。</span></span><br><span class="line">-(<span class="type">void</span>)viewDidAppear:(<span class="type">BOOL</span>)animated;</span><br><span class="line"><span class="comment">// 将要消失:view即将从supperView中移除，移除动画切换之后调用，此时已调用removeFromSuperview。此时self.view.superview还是superview为UIViewControllerWrapperView.</span></span><br><span class="line">-(<span class="type">void</span>)viewWillDisappear:(<span class="type">BOOL</span>)animated;</span><br><span class="line"><span class="comment">// 已经消失:view从superView中移除，移除动画切换之后调用，此时已调用removeFromSuperview。此时self.view.superview还是superview为nil.</span></span><br><span class="line">-(<span class="type">void</span>)viewDidDisappear:(<span class="type">BOOL</span>)animated;</span><br><span class="line"><span class="comment">// 内存警告</span></span><br><span class="line">- (<span class="type">void</span>)didReceiveMemoryWarning;</span><br><span class="line"><span class="comment">// 销毁释放</span></span><br><span class="line">-(<span class="type">void</span>)dealloc;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>如果是通过Storyboard的Segue方式<code>addChildViewController</code>或者push将要展示的ViewController,UIViewController中生命周期相关函数调用顺序如下:</p>
</li>
<li><p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-4e00bd2e7de7dc59.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>Segue.png</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-56b5776cf0515c97.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1030/format/webp" alt="img"></p>
<p>Segue方式展示vc时的生命周期.png</p>
</li>
<li><p>pop 弹出,消失销毁时,,UIViewController中生命周期相关函数调用顺序如下:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-7fdac7c3320314b5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/966/format/webp" alt="img"></p>
<p>  pop 弹出,消失销毁时,,UIViewController中生命周期.png</p>
</li>
</ul>
<hr>
<ul>
<li><p>init,push展示时调用顺序:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-5754e996f2d0d092.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>init,push展示时调用顺序.png</p>
</li>
<li><p>pop时调用顺序:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-1513804472eb2ea5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>pop时调用顺序.png</p>
</li>
</ul>
<hr>
<ul>
<li><p><code>initWithNibName</code>,通过xib初始化控制器并push展示时调用顺序:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-b8e6848b3c4b3b61.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>initWithNibName初始化控制器并展示时的生命周期.png</p>
</li>
<li><p>pop时调用顺序:</p>
</li>
</ul>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-a3b19921bcb7aa7e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1004/format/webp" alt="img"></p>
<p>xib pop时调用顺序.png</p>
<hr>
<ul>
<li>由打印结果可以看出,当加载展示ViewController时,三种方式调用是生命周期方法顺序大致相同,但是有些方法调用的还是有些不同的:<ol>
<li>通过Storyboard创建控制器并通过Segue方式展示控制器时,会调用<code>- (instancetype)initWithCoder:(NSCoder *)coder;</code>和<code>-(void)awakeFromNib;</code>方法,不会调用<code>- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ;</code>和<code>- (instancetype)init;</code>方法;</li>
<li><code>init</code>方法初始控制器并push展示控制器,会调用<code>- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ;</code>和<code>- (instancetype)init;</code>方法;不会调用<code>- (instancetype)initWithCoder:(NSCoder *)coder;</code>和<code>-(void)awakeFromNib;</code>方法</li>
<li><code>initWithNibName</code>初始化控制器并push展示,会调用<code>- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil</code>,不会调用<code>- (instancetype)init;</code>,<code>- (instancetype)initWithCoder:(NSCoder *)coder;</code>和<code>-(void)awakeFromNib;</code>方法.</li>
<li>除此以外其他生命周期方法都会调用,并且调用顺序相同.</li>
</ol>
</li>
<li>pop弹出返回上个控制器,当前控制器消失销毁时,三种方式调用的生命周期方法是一样的.</li>
<li>值得注意的是当A控制器的导航控制器<code>push</code>B控制器进来显示时,调用的顺序为:B的<code>viewDidLoad</code>,A的<code>viewWillDisappear</code>,B的<code>viewWillAppear</code>,A的<code>viewDidDisappear</code>,B的<code>viewDidAppear</code>;当B的导航控制器pop当前控制器,返回展示A控制器时,调用顺序:B的<code>viewWillDisappear</code>,A的<code>viewWillAppear</code>,B的<code>viewDidDisappear</code>,A的<code>viewDidAppear</code>,B的<code>dealloc</code>.</li>
<li><code>viewWillLayoutSubviews</code>和<code>viewDidLayoutSubviews</code>方法会在<code>viewWillAppear</code>和<code>viewDidAppear</code>之间调用,并且可能会被调用多次.</li>
<li>上面打印顺序都是基于不去变动self.view的情况下,如果是<code>initWithCoder</code>归档的方式初始化控制器,在方法内访问<code>self.view</code>的<code>getter</code>方法,会调用<code>[self loadview]</code>方法,此时会坏内存访问报错<code>Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)</code>,但是可以在次创建初始化<code>self.view</code>,设置frame并不影响最终展示的位置和大小,但可以设置其他属性如背景颜色,并且该创建的view会将归档中的视图替换掉.一点创建了<code>self.view</code>,会优先调用<code>viewDidLoad</code>方法,然后调用<code>awakeFromNib</code>,并且不再调用<code>loadView</code>方法.<code>awakeFromNib</code>方法中默认也并没有创建<code>self.view</code>,如果在<code>awakeFromNib</code>方法中访问<code>self.view</code>的<code>getter</code>方法也会调用<code>[self loadview]</code>方法,但不会报错,说明在此起价已经初始化了<code>self.view</code>,然后在<code>loadview</code>中去加载<code>self.view</code>;</li>
</ul>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">instancetype</span>)initWithCoder:(<span class="built_in">NSCoder</span> *)aDecoder &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">self</span> = [<span class="variable language_">super</span> initWithCoder:aDecoder]) &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;%@: %s&quot;</span>,<span class="built_in">NSStringFromClass</span>([<span class="keyword">self</span> <span class="keyword">class</span>]) ,__func__);</span><br><span class="line">        <span class="keyword">self</span>.view = [<span class="built_in">UIView</span> new];</span><br><span class="line">        <span class="keyword">self</span>.view.frame = <span class="built_in">CGRectMake</span>(<span class="number">0</span>, <span class="number">88</span>, <span class="number">100</span>, <span class="number">200</span>);</span><br><span class="line">        <span class="keyword">self</span>.view.backgroundColor = <span class="built_in">UIColor</span>.greenColor;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-3827757aec268d9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>initWithCoder方法中创建的self.view.png</p>
<ul>
<li><code>init</code>方法初始化控制器时,如果在<code>initWithNibName</code>中访问 <code>self.view</code>的gettter方法,会先调用<code>loadView</code>和<code>viewDidLoad</code>方法,然后才调用<code>init</code>方法;如果是在<code>init</code>方法或者<code>initWithNibName</code>方法手动初始化了<code>self.view</code>,则不再调用<code>loadView</code>和<code>viewDidLoad</code>方法;</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil &#123;</span><br><span class="line">    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) &#123;</span><br><span class="line">        NSLog(@&quot;%@: %s&quot;,NSStringFromClass([self class]) ,__func__);</span><br><span class="line">         self.view.backgroundColor = UIColor.greenColor;</span><br><span class="line">    &#125;</span><br><span class="line">    return self;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-8af100a437bc3f9b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>initWithNibName方法中重写self.view的getter方法.png</p>
<ul>
<li><p>总的来说,默认会在<code>loadView</code>中通过懒加载的方式加载<code>self.view</code>,如果在之前的方法中访问<code>self.view</code>的getter方法会触发调用<code>loadView</code>方法,如果重写初始化<code>self.view</code>的方法(getter方法).则不会再调用<code>loadView</code>方法;如果是加载系统的<code>self.view</code>,重写时需要调用<code>[super loadView]</code>,如果是自定义的<code>self.view</code>(自己创建的),则不需要调用<code>[super loadView]</code>.</p>
</li>
<li><p>控制器的</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">self.view</span><br></pre></td></tr></table></figure>

<p>的superview是在</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">viewWillAppear</span><br></pre></td></tr></table></figure>

<p>添加的,</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">window</span><br></pre></td></tr></table></figure>

<p>是在</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">viewWillLayoutSubviews</span><br></pre></td></tr></table></figure>

<p>添加的;如下图:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-aa6e8c1f2962bca8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>self.view的superview和window添加时机.png</p>
</li>
</ul>
<h2 id="UIView的生命周期"><a href="#UIView的生命周期" class="headerlink" title="UIView的生命周期"></a>UIView的生命周期</h2><ul>
<li>UIView生命周期相关函数:</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">//构造方法,初始化时调用,不会调用init方法</span><br><span class="line">- (instancetype)initWithFrame:(CGRect)frame;</span><br><span class="line">//添加子控件时调用</span><br><span class="line">- (void)didAddSubview:(UIView *)subview ;</span><br><span class="line">//构造方法,内部会调用initWithFrame方法</span><br><span class="line">- (instancetype)init;</span><br><span class="line">//xib归档初始化视图后调用,如果xib中添加了子控件会在didAddSubview方法调用后调用</span><br><span class="line">- (instancetype)initWithCoder:(NSCoder *)aDecoder;</span><br><span class="line">//唤醒xib,可以布局子控件</span><br><span class="line">- (void)awakeFromNib;</span><br><span class="line">//父视图将要更改为指定的父视图,当前视图被添加到父视图时调用</span><br><span class="line">- (void)willMoveToSuperview:(UIView *)newSuperview;</span><br><span class="line">//父视图已更改</span><br><span class="line">- (void)didMoveToSuperview;</span><br><span class="line">//其窗口对象将要更改</span><br><span class="line">- (void)willMoveToWindow:(UIWindow *)newWindow;</span><br><span class="line">//窗口对象已经更改</span><br><span class="line">- (void)didMoveToWindow;</span><br><span class="line">//布局子控件</span><br><span class="line">- (void)layoutSubviews;</span><br><span class="line">//绘制视图</span><br><span class="line">- (void)drawRect:(CGRect)rect;</span><br><span class="line">//从父控件中移除</span><br><span class="line">- (void)removeFromSuperview;</span><br><span class="line">//销毁</span><br><span class="line">- (void)dealloc;</span><br><span class="line">//将要移除子控件</span><br><span class="line">- (void)willRemoveSubview:(UIView *)subview;</span><br></pre></td></tr></table></figure>

<hr>
<ul>
<li><p><code>init</code>方式创建视图,并添加到父视图中展示,不添加子控件,其生命周期调用顺序为:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-a2ff2c49c52fc658.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/632/format/webp" alt="img"></p>
<p>init方式创建视图.png</p>
</li>
<li><p><code>initWithFrame</code>方式创建视图,并添加到父视图中展示,不添加子控件,其生命周期调用顺序为:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-26b427d41d5e9365.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/638/format/webp" alt="img"></p>
<p>initWithFrame方式创建视图.png</p>
</li>
<li><p>移除销毁是调用顺序:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-8472b345b61f9de8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/642/format/webp" alt="img"></p>
<p>移除销毁是调用顺序.png</p>
</li>
<li><p>添加子控件展示时调用顺序:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-e45247d4e822c016.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/624/format/webp" alt="img"></p>
<p>添加子控件展示时调用顺序.png</p>
</li>
<li><p>添加子控件移除销毁时调用顺序:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-af50571cc456d399.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/620/format/webp" alt="img"></p>
<p>添加子控件移除销毁时调用顺序.png</p>
</li>
</ul>
<hr>
<ul>
<li><p>xib创建初始化视图,xib中不添加子控件时调用顺序:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-620625db59dca9d0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/570/format/webp" alt="img"></p>
<p> xib创建初始化视图,xib中不添加子控件时调用顺序.png</p>
</li>
<li><p>xib创建初始化视图,xib中添加子控件时调用顺序:</p>
</li>
</ul>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-f530f5461148025c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/578/format/webp" alt="img"></p>
<p>xib创建初始化视图,xib中添加子控件时调用顺序.png</p>
<ul>
<li><p>移除销毁时调用顺序,有子控件:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-95e978d1dc9fc074.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/586/format/webp" alt="img"></p>
<p>移除销毁时调用顺序.png</p>
</li>
</ul>
<hr>
<ul>
<li><p>UIView生命周期总结:</p>
<ol>
<li><p><code>init</code>方法初始化视图,内部会调用<code>initWithFrame</code>方法,不会调用<code>initWithCoder</code>和<code>awakeFromNib</code>方法;</p>
</li>
<li><p>xib归档创建视图会触发<code>initWithCoder</code>和<code>awakeFromNib</code>方法,不再调用<code>init</code>和<code>initWithFrame</code>方法;</p>
</li>
<li><p>添加视图调用<code>addSubview</code>方法会触发<code>didAddSubview</code>犯法.</p>
</li>
<li><p><code>willMoveToSuperview</code>和<code>didMoveToSuperview</code>方法,父类变化时，无论是添加到父视图还是移除父视图都会调用;在添加时<code>willMoveToSuperview</code>的<code>newSuperview</code>即为要将要添加的父视图,此时视图的<code>superview</code>为nil,当执行<code>didMoveToSuperview</code>时,视图的父视图不再为nil,为刚添加的<code>newSuperview</code>;移除时<code>willMoveToSuperview</code>的<code>newSuperview</code>为<code>nil</code>,<code>didMoveToSuperview</code>时,视图的父视图也为<code>nil;</code></p>
</li>
<li><pre><code>willMoveToWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">和</span><br><span class="line"></span><br></pre></td></tr></table></figure>
didMoveToWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">方法,是持有的</span><br><span class="line"></span><br></pre></td></tr></table></figure>
window
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">变化时调用,无论是添加 到窗口显示还是移除窗口消失销毁都会调用;当添加时</span><br><span class="line"></span><br></pre></td></tr></table></figure>
willMoveToWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">的</span><br><span class="line"></span><br></pre></td></tr></table></figure>
newWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">参数不为</span><br><span class="line"></span><br></pre></td></tr></table></figure>
nil
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">,</span><br><span class="line"></span><br></pre></td></tr></table></figure>
self.window
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">却为nil,</span><br><span class="line"></span><br></pre></td></tr></table></figure>
didMoveToWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">的</span><br><span class="line"></span><br></pre></td></tr></table></figure>
self.window
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">即为</span><br><span class="line"></span><br></pre></td></tr></table></figure>
newWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">;移除时</span><br><span class="line"></span><br></pre></td></tr></table></figure>
willMoveToWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">的</span><br><span class="line"></span><br></pre></td></tr></table></figure>
newWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">参数为</span><br><span class="line"></span><br></pre></td></tr></table></figure>
nil
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">,</span><br><span class="line"></span><br></pre></td></tr></table></figure>
didMoveToWindow
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">的</span><br><span class="line"></span><br></pre></td></tr></table></figure>
self.window
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">也为</span><br><span class="line"></span><br></pre></td></tr></table></figure>
nil
</code></pre>
<p>,具体见下图:</p>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-cbf88c362e0bdf57.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>image.png</p>
</li>
<li><p>也就是说在添加到父视图时会在<code>willMoveToSuperview</code>方法中将视图添加到父视图中,在<code>willMoveToWindow</code>添加到<code>window</code>中才能展示,而在移除时在<code>willMoveToWindow</code>将当前持有的<code>window</code>置<code>nil</code>,再在<code>willMoveToSuperview</code>中将父视图置<code>nil</code>;</p>
</li>
<li><p>在调用<code>removeFromSuperview</code>方法时,其<code>superview</code>已经设置为<code>nil</code>,<code>willRemoveSubview</code>方法在<code>dealloc</code>方法之后调用,但是此时self并没有销毁,并不为<code>nil</code>,应该是<code>runloop</code>还没有切换导致的(还未验证).</p>
</li>
</ol>
</li>
</ul>
<h2 id="UIViewController和UIView进入展示时整体生命周期调用顺序"><a href="#UIViewController和UIView进入展示时整体生命周期调用顺序" class="headerlink" title="UIViewController和UIView进入展示时整体生命周期调用顺序"></a>UIViewController和UIView进入展示时整体生命周期调用顺序</h2><ul>
<li><code>self.view</code>是控制器的默认视图,<code>NoXibView</code>是添加到<code>self.view</code>的子视图,UIViewController和UIView加载展示时整体生命周期调用顺序如下(红色为打印的生命周期方法,蓝色的为superview和window):</li>
</ul>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-b428ecf91abf7b8a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>UIViewController和UIView加载展示时整体生命周期调用顺序.png</p>
<ol>
<li>vc(控制器)的<code>viewDidLoad</code>方法;</li>
<li><code>NoXibView</code>的<code>willMoveToSuperview</code>和<code>didMoveToSuperview</code>,此时已将<code>NoXibView</code>添加到父视图上;</li>
<li>vc的<code>viewWillDisappear</code>方法,促使vc的view的superview和window还是为nil;</li>
<li><code>NoXibView</code>的<code>willMoveToWindow</code>和<code>didMoveToWindow</code>,此时已将<code>NoXibView</code>添加到<code>widonw</code>;</li>
<li>vc的<code>viewWillLayoutSubviews</code> ,此时<code>vc</code>的<code>view</code>的<code>superview</code>和<code>window</code>不再为nil;</li>
<li>vc的<code>viewDidLayoutSubviews</code> ;</li>
<li><code>NoXibView</code>的<code>layoutSubviews</code>;</li>
<li>vc的<code>viewDidAppear</code> .</li>
</ol>
<ul>
<li>UIViewController和UIView消失销毁时整体生命周期调用顺序如下:</li>
</ul>
<p><img src= "" data-lazy-src="https://upload-images.jianshu.io/upload_images/2056699-0797755becb1e63e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt="img"></p>
<p>UIViewController和UIView消失销毁时整体生命周期调用顺序.png</p>
<ol>
<li>vc的viewWillDisappear;</li>
<li><code>NoXibView</code>的<code>willMoveToWindow</code>,<code>didMoveToWindow</code>,此时<code>NoXibView</code>的window置nil;</li>
<li>vc的<code>viewDidDisappear</code>;此时vc的view的window和superview都置为nil;</li>
<li>vc的’dealloc’;</li>
<li><code>NoXibView</code>的<code>willMoveToSuperview</code>和<code>didMoveToSuperview</code>,此时<code>NoXibView</code>的<code>superview</code>置nil;</li>
<li><code>NoXibView</code>的<code>removeFromSuperview</code>;</li>
<li><code>NoXibView</code>的’dealloc’;</li>
<li><code>NoXibView</code>的’willRemoveSubview’.</li>
</ol>
<ul>
<li>总而言之加载展示时:就是先将子控件添加到当前控件中,再将子控件添加到<code>window</code>,然后将当前控件添加到父控件中,再将当前控件添加到<code>window</code>中;移除销毁时:将当前空前的window置nil,再将父控件置nil,将当前控件移除销毁,再将子控件的window置nil,子控件的父控件置nil;(展示时先添加子控件再添加当前控件再添加父控件,移除时先移除父控件,再移除当前控件,再移除子控件).</li>
</ul>
<h2 id="开发技巧总结"><a href="#开发技巧总结" class="headerlink" title="开发技巧总结"></a>开发技巧总结</h2><ul>
<li>在开发中很多方法是用不到的,所以也没必要都记顺序,上面之所以要打印superview和window,是因为不管是autoresize还是autolayout布局都是基于父视图的,wiondw是最终的显示载体;</li>
<li>对于<code>UIViewController</code>,<code>viewDidLoad:</code>方法是视图加载完成,我们可以在里面添加子视图,设置相关属性和布局等,所有和self.view相关的操作在该方法中添加比较合适;<code>viewWillAppear:</code>视图即将显示时调用;<code>viewWillLayoutSubviews:</code>视图将要布局其子视图时被调用;<code>viewDidLaySubviews:</code>视图布局完成其子视图时被调用;<code>viewDidAppear</code>视图显示后被调用;<code>viewWillDisappear:</code>视图将要消失时调用;<code>viewDidDisappear:</code>视图已经消失时调用;</li>
<li><code>注意</code>:<code>viewWillAppear:</code>和<code>viewWillDisappear:</code>有时要成对使用;<code>viewDidAppear</code>和<code>viewDidDisappear:</code>有时要成对使用,比如显示该页面定位,消失时结束定位;还比如该页面显示时影藏导航,去其他页面时恢复导航;</li>
<li><code>UIView</code>的<code>layoutSubviews</code>会被经常调用,下面说下layoutsubview的调用情况：<br> 1、addSubview会触发layoutSubviews，如果addSubview 如果连续2个 只会执行一次，具体原因下面说。<br> 2、设置view的Frame会触发layoutSubviews，必须是frame的值设置前后发生了变化。<br> 3、滚动一个UIScrollView会触发layoutSubviews。<br> 4、旋转Screen会触发父UIView上的layoutSubviews事件。<br> 5、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件。</li>
<li>如果要立即执行<code>layoutsubview</code> ,要先调用[view setNeedsLayout]，把标记设为需要布局，然后马上调用[view layoutIfNeeded]，实现布局.其中的原理是：执行setNeedsLayout后会在receiver标上一个需要被重新布局的标记，在系统runloop的下一个周期自动调用layoutSubviews。这样刷新会产生延迟，所以我们需要马上执行layoutIfNeeded。就会开始遍历subviews的链，判断该receiver是否需要layout。如果需要立即执行<code>layoutsubview</code>.</li>
<li>每一个视图只能有唯一的一个父视图。如果当前操作视图已经有另外的一个父视图，则addsubview的操作会把它先从上一个父视图中移除（包括响应者链），再加到新的父视图上面。</li>
<li>并且连续2次的addSubview，只会执行一次layoutsubview。因为一次的runLoop结束后，如果有需要刷新，执行一次即可</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Albert Yuan</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yllove.gitee.io/2022/10/28/iOS/iOS-ViewController%E4%B8%8EView%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/">https://yllove.gitee.io/2022/10/28/iOS/iOS-ViewController%E4%B8%8EView%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yllove.gitee.io" target="_blank">Albert Yuan's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/Objective-c/">Objective-c</a><a class="post-meta__tags" href="/blog/tags/Foundation/">Foundation</a></div><div class="post_share"><div class="social-share" data-image="/blog/img/defaultCover.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2022/10/21/iOS/iOS%20description%E4%B8%8EdebugDescription%E5%9C%A8%E8%B0%83%E8%AF%95%E7%A8%8B%E5%BA%8F%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8/"><img class="prev-cover" src= "" data-lazy-src="/blog/img/defaultCover.png" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">iOS description与debugDescription在调试程序中的应用</div></div></a></div><div class="next-post pull-right"><a href="/blog/2022/11/04/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E8%87%AA%E5%8A%A8%E5%8C%96%E6%89%93%E5%8C%85%E4%B9%8Bfastlane/"><img class="next-cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1345654-f27701c6da64262b.png%3FimageMogr2%2Fauto-orient%2Fstrip%257CimageView2%2F2%2Fw%2F1240&amp;refer=http%3A%2F%2Fupload-images.jianshu.io&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1670155153&amp;t=9df0930adc7e55112de00dc7c84f6f6b" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">iOS 自动化打包之fastlane</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2021/10/12/iOS/ios定时器之NSTimer/" title="ios定时器之NSTimer"><img class="cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0119b95d5ba91aa80120695c98f29a.png&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1636599433&t=9db5e85b7ff3612a40187f12b62acd11" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-10-12</div><div class="title">ios定时器之NSTimer</div></div></a></div><div><a href="/blog/2021/08/10/iOS/ios-OC的多态/" title="ios Objective-c的多态理解"><img class="cover" src= "" data-lazy-src="https://img0.baidu.com/it/u=1459462488,4026553309&fm=26&fmt=auto&gp=0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-10</div><div class="title">ios Objective-c的多态理解</div></div></a></div><div><a href="/blog/2021/08/26/iOS/启动引导页/" title="启动引导页"><img class="cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F9463efc372704f16be50f4ed048109fadc01ff792dece-xClCWF_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1632538996&t=9535dbf2109e55b167748c259b88298d" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-26</div><div class="title">启动引导页</div></div></a></div><div><a href="/blog/2021/10/26/iOS/苹果第三方登录/" title="苹果第三方登录"><img class="cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fupload-images.jianshu.io%2Fupload_images%2F1625283-e61716c6b5265137.png&refer=http%3A%2F%2Fupload-images.jianshu.io&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637827636&t=1d207d66ff8d9377112e4eaef5dd90a5" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-10-26</div><div class="title">苹果第三方登录</div></div></a></div><div><a href="/blog/2022/09/16/iOS/ios-keychain理解与使用/ios-keychain理解与使用/" title="ios keychain理解与使用"><img class="cover" src= "" data-lazy-src="/blog/img/defaultCover.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-09-16</div><div class="title">ios keychain理解与使用</div></div></a></div><div><a href="/blog/2022/10/21/iOS/iOS description与debugDescription在调试程序中的应用/" title="iOS description与debugDescription在调试程序中的应用"><img class="cover" src= "" data-lazy-src="/blog/img/defaultCover.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-21</div><div class="title">iOS description与debugDescription在调试程序中的应用</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Albert Yuan</div><div class="author-info__description">博学之,审问之,慎思之,明辨之,笃行之</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/yuanliangYL"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yuanliangYL" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:yuanliangios@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="qq:1023817403" target="_blank" title="QQ"><i class="fab fa-qq"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">love cat , love life</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-text"></span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#UIView%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-text">UIView的生命周期</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#UIViewController%E5%92%8CUIView%E8%BF%9B%E5%85%A5%E5%B1%95%E7%A4%BA%E6%97%B6%E6%95%B4%E4%BD%93%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E8%B0%83%E7%94%A8%E9%A1%BA%E5%BA%8F"><span class="toc-text">UIViewController和UIView进入展示时整体生命周期调用顺序</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%80%E5%8F%91%E6%8A%80%E5%B7%A7%E6%80%BB%E7%BB%93"><span class="toc-text">开发技巧总结</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包"><img src= "" data-lazy-src="https://img.mp.itc.cn/upload/20170409/1a8f793d7282451cbd1beb6841608c90_th.jpeg" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 自定义网页下载IPA包"/></a><div class="content"><a class="title" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包">iOS 自定义网页下载IPA包</a><time datetime="2023-02-07T02:46:29.851Z" title="更新于 2023-02-07 10:46:29">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS"><img src= "" data-lazy-src="https://pic4.zhimg.com/v2-6a115fea4db1ad770dccf4119bfab36f_1440w.jpg?source=172ae18b" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="flutter接入原生-iOS"/></a><div class="content"><a class="title" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS">flutter接入原生-iOS</a><time datetime="2023-02-07T01:18:53.661Z" title="更新于 2023-02-07 09:18:53">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP"><img src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.winwin7.com%2Fuploadfile%2F2021%2F0114%2F20210114141748239.jpg&amp;refer=http%3A%2F%2Fwww.winwin7.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1673854539&amp;t=aad2108ffb799b04e94a28cc58f038f1" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 如何在模拟器中安装APP"/></a><div class="content"><a class="title" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP">iOS 如何在模拟器中安装APP</a><time datetime="2022-12-17T07:48:56.594Z" title="更新于 2022-12-17 15:48:56">2022-12-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库"><img src= "" data-lazy-src="https://photos.infinum.com/store/b558bd40787ecad225d9c66322f14522" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="swift常用三方库"/></a><div class="content"><a class="title" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库">swift常用三方库</a><time datetime="2022-12-16T06:37:20.115Z" title="更新于 2022-12-16 14:37:20">2022-12-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup"><img src= "" data-lazy-src="/blog/img/defaultCover.png" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="GCD进阶之DispatchWorkItem和DispatchGroup"/></a><div class="content"><a class="title" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup">GCD进阶之DispatchWorkItem和DispatchGroup</a><time datetime="2022-12-12T07:19:37.277Z" title="更新于 2022-12-12 15:19:37">2022-12-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/blog/img/defaultCover.png')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Albert Yuan</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcom to my  blog</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://fastly.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/blog/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://fastly.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'REc8eytE1gJDl3d8FkudLNlL-gzGzoHsz',
      appKey: 'gGO3y8I9oVlc4Cd5N1fizNPW',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://fastly.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="255,0,0" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>